﻿using Newtonsoft.Json;

namespace Basic.Base.Serialization;

/// <summary>
/// Default json serializer.
/// </summary>
public class DefaultJsonSerializer : ISerializer
{
    //private readonly JsonSerializerOptions JsonOption = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, DictionaryKeyPolicy = JsonNamingPolicy.CamelCase };

    /// <summary>
    /// Gets the name.
    /// </summary>
    /// <value>The name.</value>
    public string Name => SerializerConst.Json;

    /// <summary>
    /// Deserialize the specified bytes.
    /// </summary>
    /// <returns>The deserialize.</returns>
    /// <param name="bytes">Bytes.</param>
    /// <typeparam name="T">The 1st type parameter.</typeparam>
    public T Deserialize<T>(byte[] bytes)
    {
        return bytes == null ? default(T) : JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(bytes));
        //return bytes == null ? default(T) : JsonSerializer.Deserialize<T>(bytes, JsonOption);
    }

    /// <summary>
    /// Deserialize the specified bytes.
    /// </summary>
    /// <returns>The deserialize.</returns>
    /// <param name="bytes">Bytes.</param>
    /// <param name="type">Type.</param>
    public object Deserialize(byte[] bytes, Type type)
    {
        return bytes == null ? null : JsonConvert.DeserializeObject(Encoding.UTF8.GetString(bytes), type);
        //return bytes == null ? null : JsonSerializer.Deserialize(bytes, type, JsonOption);
    }

    /// <summary>
    /// Serialize the specified value.
    /// </summary>
    /// <returns>The serialize.</returns>
    /// <param name="value">Value.</param>
    /// <typeparam name="T">The 1st type parameter.</typeparam>
    public byte[] Serialize<T>(T value)
    {
        return value == null ? null : Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value));
        //return value == null ? null : JsonSerializer.SerializeToUtf8Bytes(value, JsonOption);
    }

    /// <summary>
    /// Serializes the object.
    /// </summary>
    /// <returns>The object.</returns>
    /// <param name="obj">Object.</param>
    public byte[] SerializeObject(object obj)
    {
        return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(obj));
    }

}